package com.lvxtech.gateway.common.filter;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR;

import java.util.List;
import java.util.function.Function;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.MDC;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Email miles02@163.com
 *
 * @author fangzhipeng
 * create 2018-11-16
 **/
public class GlobalRequestIdFilter implements GlobalFilter, Ordered {
	
	public static final String REQUEST_ID = "requestId";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    	String requestId = getHeaderRequestId(exchange.getRequest());
    	MDC.put(REQUEST_ID, requestId);
    	exchange.getAttributes().put(REQUEST_ID, requestId);
//    	exchange.getRequest().getHeaders().add(REQUEST_ID, requestId);
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                	String requestId2 = exchange.getAttribute(REQUEST_ID);
					if (requestId2 != null) {
						MDC.put(REQUEST_ID, null);
					}
                })
        );
    }

    private String getHeaderRequestId(ServerHttpRequest request) {
    	List<String> rqs = request.getHeaders().get(REQUEST_ID);
    	if(rqs==null||rqs.isEmpty()){
    		return getRequestId(request);
    	}
		return rqs.get(0);
	}
    
    private String getRequestId(ServerHttpRequest request) {
    	return String.valueOf(request.getURI().hashCode()+request.hashCode());
	}

	@Override
    public int getOrder() {
        return -100;
    }
}
